// import { AsyncStorage, DeviceEventEmitter, Alert } from 'react-native'
import merchantApi, {CustomerInfoVO} from './merchant'
import Taro from '@tarojs/taro'

export type CustomerType = 'PLATFORM' | 'MERCHANT'
export type PageType =
  //智慧营养
  | 'NUTRITION_LIST' /**所有测评列表页 */
  | 'NUTRITION_DETAIL' /**测评详情页 */
  | 'NUTRITION_VIP' /**智慧营养会员直通车页 */
  | 'NUTRITION_FORM' /**测评填写步骤页 */
  | 'NUTRITION_REPORT' /**报告详情页面 */
  | 'NUTRITION_ORDER' /**智慧营养订单详情页面 */
  //店铺客服 以下三个类别 resourceId 必填
  | 'MERCHANT_SHOP' /**店铺主页  resourceId 对应 店铺ID*/
  | 'MERCHANT_PRODUCT' /**商品详情页 resourceId 对应 商品ID*/
  | 'MERCHANT_ORDER' /**订单详情页 resourceId 对应 订单ID*/
  //讲堂
  | 'LECTURE_CREATE' /**讲师创建课堂失败提示弹窗 */
  | 'LECTURE_DETAIL' /**付费课堂详情界面  resourceId 对应 课程ID*/
  //个人中心
  | 'PERSONAL_CENTER_WALLET' /**我的钱包-常见问题 */
  | 'PERSONAL_CENTER_CUSTOMER' /**个人中心-联系客服 */
export interface CustomerServiceParams {
  /**
   * 商城 店铺 调用时候传 MERCHANT
   * 其他传 PLATFORM
   */
  customerType: CustomerType
  pageType: PageType
  resourceId?: string
}

const CUSTOMER_SERVICE_STORAGE_KEY = 'CUSTOMER_SERVICE_STORAGE_KEY'

const queryChatInfo = async (params: CustomerServiceParams): Promise<CustomerInfoVO> => {
  const res: CustomerInfoVO = await merchantApi.customers.info(params)
  if (res) {
    insertOrRelpaceData(res)
  }
  return res
}

const queryAllData = () => {
  try {
    const value = Taro.getStorageSync(CUSTOMER_SERVICE_STORAGE_KEY)
    if (value) {
      // console.log(value, 'pp')
      return JSON.parse(value)
    }
  } catch (ex) {}
}

const queryData = async (customerId: string) => {
  // let data = await AsyncStorage.getItem(CUSTOMER_SERVICE_STORAGE_KEY)
  await Taro.getStorage({
    key: CUSTOMER_SERVICE_STORAGE_KEY,
    success: function (res) {
      const newData = JSON.parse(res.data)
      if (newData && Array.isArray(newData)) {
        const data = newData.find((model) => model.customerId === customerId)
        return data
      } else {
        return newData
      }
    },
  })
}
const insertMsg = (info: CustomerInfoVO) => {
  // console.log(info, 'info')
}

const insertOrRelpaceData = (info: CustomerInfoVO) => {
  Taro.getStorage({
    key: CUSTOMER_SERVICE_STORAGE_KEY,
    success: function (res) {
      if (res.data) {
        let newData = JSON.parse(res.data)
        if (newData && Array.isArray(newData)) {
          const index = newData.findIndex((res) => {
            return res.customerId === info.customerId
          })
          if (index != -1 && newData.length > index) {
            newData[index] = info
          } else {
            newData.push(info)
          }
        } else {
          newData = [info]
        }
      }
    },
    fail: function (ex) {
      console.log(ex)
      Taro.setStorage({
        key: CUSTOMER_SERVICE_STORAGE_KEY,
        data: JSON.stringify([info]),
      })
    },
  })
}
const removeAllData = () => {
  // AsyncStorage.removeItem(CUSTOMER_SERVICE_STORAGE_KEY)
  Taro.removeStorage({
    key: CUSTOMER_SERVICE_STORAGE_KEY,
    success: function () {
      console.log('success')
    },
  })
}

const removeData = (customerId: string) => {
  Taro.getStorage({
    key: CUSTOMER_SERVICE_STORAGE_KEY,
    success: function (res) {
      const newData = JSON.parse(res.data)

      if (newData && Array.isArray(newData)) {
        const index = newData.findIndex((model) => model.customerId === customerId)
        if (newData.length > index && index != -1) {
          newData.splice(index, 1)
        }
        Taro.setStorage({
          key: CUSTOMER_SERVICE_STORAGE_KEY,
          data: JSON.stringify(newData),
        })
        // AsyncStorage.setItem(CUSTOMER_SERVICE_STORAGE_KEY, JSON.stringify(newData))
      } else {
        Taro.removeStorage({
          key: CUSTOMER_SERVICE_STORAGE_KEY,
          success: function (res) {
            console.log(res)
          },
        })
      }
    },
  })
}

export {
  queryChatInfo,
  queryAllData,
  queryData,
  insertOrRelpaceData,
  insertMsg,
  removeAllData,
  removeData,
}
